package JUC_Advanced.chapter1_CompletableFuture;

import java.util.concurrent.*;

/**
 * @Author: GuSongLiao
 * @Date: 2024/3/6 14:14
 * @Description: 创建第一个异步线程
 */
public class CompletableFutureDemo {


    public static void main(String[] args) throws ExecutionException, InterruptedException, TimeoutException {




        FutureTask<String> futureTask = new FutureTask<>(new MyThread());

        new Thread(futureTask, "t1").start();

        System.out.println(futureTask.get());


        ExecutorService executorService = Executors.newFixedThreadPool(3);
        FutureTask<String> futureTask1 = new FutureTask<>(() -> {
            TimeUnit.SECONDS.sleep(5);
            return "hello callable";
        });

        executorService.submit(futureTask1);

//        System.out.println(futureTask1.get()); // get()方法会阻塞当前线程，直到任务执行完成  一般放置在最后

        /**
         * 阻塞时间最多等待 3秒钟，过时不候 否则会抛出异常
         * Exception in thread "main" java.util.concurrent.TimeoutException
         * 	at java.util.concurrent.FutureTask.get(FutureTask.java:205)
         * 	at JUC_Advanced.chapter1.CompletableFutureDemo.main(CompletableFutureDemo.java:34)
         */
        System.out.println(futureTask1.get(3, TimeUnit.SECONDS));
    }




}

class MyThread implements Callable<String> {
    @Override
    public String call() throws Exception {
        return "hello callable";
    }
}
